<template>
	<view class="matchmain animated fadeIn faster">
		<view class="position-fixed w-100 z-index-100 pb-1" :style="{'paddingTop':$store.state.statusBarHeight+'px','backgroundColor':bgcolor}">
			<view class="d-flex d-flex-middle d-flex-between" :style="{'height': $store.state.titleBarHeight + 'px'}">
				<view class="pl-2" @click="goBack"><text class="iconfont icon-31fanhui1 font30 colorfff"></text></view>
				<view class="colorfff">{{chooseGame}}</view>
				<text class="iconfont icon-31fanhui1 font30 colorfff vhiden"></text>
			</view>
		</view>
		<view :style="{paddingTop:$store.state.statusBarHeight+'px',height: $store.state.titleBarHeight + 'px'}"></view>
		<view class="d-flex d-flex-middle d-flex-between mt-3 mb-4">
			<view class="pl-2 d-flex d-flex-middle" @click="prev" style="height: 82rpx;">
				<text class="iconfont icon-left-circle colorfff"></text>
			</view>
			<swiper class="d-flex-item" :current="current" @change="swiperChange" style="height: 82rpx;">
				<swiper-item v-for="(avalist,aindex) in avatarList" :key="aindex">
					<view class="d-flex-item d-flex d-flex-middle d-flex-between mx-2">
						<image class="avatarImg" 
							   :class="{'avatarImgCur': avaIndex == avadex && aindex == currentArrayIndex}" 
							   v-for="(avatar,avaIndex) in avalist"
							   :key="avatar.id" :src="avatar.icon" 
							   @click="changGame(aindex,avaIndex)" 
							   style="width: 70rpx;height: 70rpx;border-radius: 20rpx;"
						></image>
					</view>
				</swiper-item>
			</swiper>
			<view class="pr-2 d-flex d-flex-middle" @click="next" style="height: 82rpx;">
				<text class="iconfont icon-right-circle-copy colorfff"></text>
			</view>
		</view>
		<view class="d-flex d-flex-center mb-8">
			<qiu-tag></qiu-tag>
		</view>
		<view class="d-flex d-flex-center mb-7">
			<text class="colorfff">当前</text>
			<text class="colorman"> {{ count }} </text>
			<text class="colorfff">人在线</text>
		</view>
		<view class="d-flex d-flex-center d-flex-middle mb-5" @click="gotoDaziCard">
			<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/encard.png" mode="widthFix" style="width: 230rpx;"></image>
			<text class="colorfff">性别卡/性格卡/同城卡</text>
		</view>
		<view class="px-2 d-flex d-flex-between pb-5">
			<view class="left-bg" @click="gotoChoseDazi">
				<view class="font30 colorfff mb-1">搭子匹配</view>
				<view class="bg-fff rounded30 d-flex d-flex-center d-flex-middle colorman font20" style="width: 120rpx;height: 40rpx;">开始匹配</view>
			</view>
			<view class="right-bg d-flex d-flex-column d-flex-between">
				<view class="right-up d-flex d-flex-between" @click="openFilterPopup('center')">
					<view class="d-flex d-flex-column d-flex-between">
						<text class="font30 colorfff">筛选类别</text>
						<text class="iconfont icon-youjiantou-tianchong colorfff font30"></text>
					</view>
					<view class="d-flex d-flex-bottom pr">
						<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/team2211.png" mode="widthFix" style="width: 120rpx"></image>
					</view>
				</view>
				<view class="right-down d-flex d-flex-between" @click="gotoDaziCard">
					<view class="d-flex d-flex-column d-flex-between">
						<text class="font30 colorfff">功能卡</text>
						<text class="iconfont icon-youjiantou-tianchong colorfff font30"></text>
					</view>
					<view class="d-flex d-flex-bottom pr-3">
						<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/team2223.png" mode="widthFix" style="width: 66rpx"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="position-absolute" style="right: 0rpx; top: 280rpx;" @click="gotoDaziBell">
			<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/bell3.gif" style="width: 100rpx; height: 100rpx;"></image>
		</view>
		<uni-popup ref="FilterPopup" background-color="#fff" border-radius="16px 16px 16px 16px" class="position: relative;">
			<view class="title font34 text-center w-100 font-bold bg-fff" style="border-radius: 16px 16px 0 0; height: 80rpx; line-height: 80rpx; width: 720rpx;">筛选</view>
			<view style="height: 60vh; overflow: scroll; width: 720rpx;" class="Popup-Wapper">
				<view class="popup-content p-2 mt-1" v-for="(record, index) in purpose" :key="index">
					<view class="comtitle bg-f5 p-2 rounded30" style="width: 95%;">
						<view class="title row d-flex-between mb-2">
							<text class="font30 font-bold">{{ record.name }}</text>
							<text style="color: #9D9D9E; vertical-align: bottom;" class="font22 mr-3">{{record.name=='段位名称'||record.name=='搭子类型'||record.name=='同城'||record.name=='性别'||record.name=='性格'?"单选":"多选"}}</text>
						</view>
						<view class="d-flex d-flex-wrap d-flex-between">
							<view class="xuanzhe" :class="selectedPurpose.some(selectedItem => selectedItem.id === item.id) ? 'onxz' : ''" v-for="(item,index) in record.items" style="color: black;" :key="index" @click="choosePurpose(item,record.name,record.description)">{{item.name}}</view>
						</view>
					</view>
				</view>
				<view class="d-flex d-flex-between py-2 position-absolute" style="bottom: 0rpx; width: 100%; background: #fff; border-radius: 0 0 16rpx 16rpx;">
					<view class="reset font32 py-2 ml-2 rounded50 span-9 text-center" style="background-color: #F3F5FA;" @click="reset" >重置</view>
					<view class="confirm font32 py-2 mr-2 rounded50 span-9 text-center" style="background: linear-gradient(to right, #249CFF, #274BFF); color: #fff;" @click="closeFilterPopup">确定</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="TipsPopup" type="dialog" style="position: relative; z-index: 999999;">
			<uni-popup-dialog cancelText="取消" confirmText="去发布" title="提示" content="您当前没有发布当前搭子卡,是否需要去发布？"
				@confirm="confirmTips" @close="colseTipsPopup"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import { goodsApi } from "../../http/goodsApi";
	import { DaziApi } from "../../http/Dazi"
	import { DictionaryApi } from '../../http/dictionary';
	import { manner } from "@/util/manner.js";
	import qiuTag from '@/components/qiu-tag/qiu-tag.vue';
	import {dateUtils} from '@/util/util.js';
	export default {
		data() {
			return {
				bgcolor:'transparent',
				current:0,
				avatarList:[],
				count: null,
				timer: null,
				gameId: null,
				purpose:[],
				DaziCardList: [],
				chooseGame: '',//选择的游戏
				currentArrayIndex: 0, // 当前选中的数组索引
				selectedPurpose: [],//选择的目的
				avadex: 0,
				isContinue: true
			}
		},
		onPageScroll(e) {
			let scrollTop = e.scrollTop
			if (scrollTop > 10) {
				this.bgcolor = '#191635'
			}else{
				this.bgcolor = 'transparent'
			}
		},
		onLoad() {
			this.getAvatarList()
			this.count = Math.floor(Math.random() * (120000 - 110000 + 1)) + 110000;
			this.timer = setInterval(() => {
			    this.updateCount()
			}, 1000)
		},
		methods: {
			// 查询交友目的等
			async getFilter() {
				const param = {
					gameId: this.gameId
				}
				let res = await goodsApi.queryGamesFilter(param);
				let recods = res.items
				let SameCity = {
					items: [{id: "0", name: "同城"},{id: "1", name: "非同城"}],
					name: "同城",
					description: "同城卡"
				}
				let Sex = {
					items: [{id: "3", name: "男"},{id: "4", name: "女"}],
					name: "性别",
					description: "性别卡"
				}
				let Character = {
					items: [{id: "5", name: "I人"},{id: "6", name: "E人"}],
					name: "性格",
					description: "性格卡"
				}
				recods.push(SameCity)
				recods.push(Sex)
				recods.push(Character)
				this.purpose = recods
				this.queryDaziCard()
			},
			updateCount() {
				let n = Math.floor(Math.random() * 19) - 9;
				this.count += n
			},
			// 查询对应搭子卡详细信息
			async queryDaziCard() {
				let params = {
					pageIndex: 1,
					pageSize: 10
				}
				const res = await DaziApi.DaziCard(params)
				this.DaziCardList = res.records
				console.log(this.DaziCardList);
			},
			goBack(){
				manner.goBack()
			},
			choosePurpose(item,name,description){ //选择的类型
				if (name === "同城"|| name === "性别"|| name === "性格") {
					this.DaziCardList.forEach((i) => {
						if(i.name === description) {
							if(i.hasBalanceFlag || this.$store.state.user.accountType!==1) {
								return
							} else {
								uni.showModal({
									content: '此选项为搭子卡和会员专属，是否需要进行购买？',
									success: function (res) {
										if (res.confirm) {
											uni.navigateTo({
												url: '/pagesMain/star-DaziCard/star-DaziCard'
											})
										}
									}
								});
								this.isContinue = false
							}
						}
					})
				}
				if(this.isContinue) {
					if (name === "段位名称" || name === "搭子类型"|| name === "同城"|| name === "性别"|| name === "性格") {
					       // 单选逻辑
					       // 移除同类型的旧选项
					       this.selectedPurpose = this.selectedPurpose.filter(i => i.typeName !== name);
					       // 添加新选项
					       this.selectedPurpose.push({ id: item.id, name: item.name, typeName: name });
					  } else {
						// 对于非“段位名称”类型，保持原有的逻辑
						const indexInSelected = this.selectedPurpose.findIndex(selectedItem => selectedItem.id === item.id);
						if (indexInSelected === -1) {
							// 如果不存在，则添加一个包含 id 和 name 的对象
							this.selectedPurpose.push({ id: item.id, name: item.name, typeName: name });
						} else {
							// 如果存在，则移除该对象
							this.selectedPurpose.splice(indexInSelected, 1);
						}
					}
				}
				this.isContinue = true
			},
			swiperChange(e){
				this.current = e.detail.current;
			},
			// 筛选
			openFilterPopup(type) {
				this.getFilter();
				this.type = type
				this.$refs.FilterPopup.open(type)
			},
			reset() {
				this.selectedPurpose = [];
			},
			closeFilterPopup() {
				uni.showToast({
					icon: 'none',
					title: '筛选成功！',
					duration: 1500
				})
				console.log(this.selectedPurpose);
				this.$refs.FilterPopup.close()
			},
			confirmTips() {
				let game = this.avatarList[this.currentArrayIndex][this.avadex]
				uni.navigateTo({
					url: `/pagesMain/edite-card/edite-card?id=${game.id}&name=${encodeURIComponent(game.name)}&icon=${encodeURIComponent(game.icon)}`
				})
			},
			colseTipsPopup() {
				this.$refs.TipsPopup.close()
			},
			gotoDaziBell() {
				uni.navigateTo({
					url:'/pagesMain/star-daziBell/star-daziBell'
				})
			},
			gotoDaziCard() {
				uni.navigateTo({
					url:'/pagesMain/star-DaziCard/star-DaziCard'
				})
			},
			async getDazi() {
				let param = {
					pageIndex: 1,
					pageSize: 11,
					uid: this.$store.state.user.uid,
					gameId: this.gameId
				}
				let res = await DaziApi.queryCard(param);
				return res.records.length
			},
			gotoChoseDazi : dateUtils.debounce(function() {
			    console.log('只能这样点击');
				this.getDazi().then((result) => {
					if(result == 0) {
						console.log(result);
						this.$refs.TipsPopup.open()
					} else {
						uni.navigateTo({
							url:'/pagesMain/chose-dazi/chose-dazi?gameId='+this.gameId+'&params='+JSON.stringify(this.selectedPurpose)
						})
					}
				})
			}, 1000),
			prev() {
				if (this.current <= 0) {
					return
				} else {
					this.current--
				}
			},
			next() {
				if (this.current >= 1) {
					uni.navigateTo({
						url: '/pagesMain/moreGames/moreGames?type=2'
					})
				} else {
					this.current++
				}
			},
			changGame(aindex, avaIndex) {
				this.currentArrayIndex = aindex; // 更新当前选中的数组索引
				this.avadex = avaIndex
				this.gameId = this.avatarList[aindex][avaIndex].id
				this.chooseGame=this.avatarList[aindex][avaIndex].name;
			},
			// 修改游戏列表数据
			addAvatar() {
				let IsRepeat = false
				let GameDada = uni.getStorageSync('game')
				for(let i=0; i<=1; i++) {
					this.avatarList[i].forEach((item, dex) => {
						if(GameDada.id == item.id) {
							this.current = i
							this.avadex = dex
							IsRepeat = true
							this.gameId = this.avatarList[0][dex].id
							return
						}
					})
				}
				if(!IsRepeat) {
					this.avatarList[0].splice(0, 1, GameDada);
					this.current = 0
					this.avadex = 0
					this.gameId = this.avatarList[0][0].id
				}
			},
			// 游戏列表数据
			async getAvatarList(){
				// let params = {
				// 	pageIndex: 1,
				// 	pageSize: 14
				// }
				// let res = await goodsApi.queryGamesList(params);
				// 使用缓存数据2
				const cached2Data = await dateUtils.getCacheWithExpire('api_data_cache2');
				let transferArr1 = []
				let transferArr2 = []
				cached2Data.forEach((i, dex) => {
					if(dex < 7) {
						transferArr1.push(i)
					} else if (dex >= 7 && dex <14){
						transferArr2.push(i)
					}
				})
				this.avatarList[0] = transferArr1
				this.avatarList[1] = transferArr2
				this.gameId = this.avatarList[0][0].id
				this.chooseGame=this.avatarList[0][0].name
				transferArr1 = null
				transferArr2 = null
			}
		},
		onUnload() {
		    clearInterval(this.timer)
		}
	}
</script>

<style scoped >
	.xuanzhe{
		border: 1px solid #C7C8C9;
		border-radius: 30rpx;
		padding:6rpx 0;
		width: 22%;
		text-align: center;
		color: #ffffff;
		font-size: 26rpx;
		margin-bottom: 20rpx;
	}
	.onxz{
		background: #CFF0FB;
		color: #46C4FF;
	}
.matchmain{
	background-image: url('https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/machbg.png');
	background-repeat: no-repeat;
	background-size: cover;
	background-position: 0 100%;
	min-height: 100vh;
}
.avatarImg{
	border-style: solid;
	border-width: 6rpx;
	border-color: transparent;
}
.avatarImgCur{
	border-color: #e65fd0;
}
.colorman{
	color:#5db0fe
}
.left-bg{
	width: 283rpx;
	height: 244rpx;
	padding: 20rpx 30rpx;
	background-image: url('https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/team3410.png');
	background-repeat: no-repeat;
	background-size: cover;
	background-position: 0 100%;
}
.right-bg{
	width: 341rpx;
	height: 284rpx;
}
.right-up{
	padding-left: 30rpx;
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	width: 311rpx;
	height: 94rpx;
	background: linear-gradient( 90deg, #5DB0FE 1%, #86F5C9 100%);
	border-radius: 30rpx;
}
.right-down{
	padding-left: 30rpx;
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	width: 311rpx;
	height: 94rpx;
	background: linear-gradient( 90deg, #D951C6 1%, #FB9AB0 100%);
	border-radius: 30rpx;
}
.uni-popup__wrapper {
	border-radius: 50rpx !important;
	overflow: scroll;
	box-sizing: border-box;
}
.popup-content {
	margin: 0 atuo;
	max-height: 70vh;
	margin-top: 10rpx;
	display: flex;
	justify-content: center;
}
.Popup-Wapper:last-child {
	padding-bottom: 100rpx;
}
.optcurrentstyle {
	border: 1px solid #46C4FF;
	background-color: #cff0fb;
	color: #46C4FF;
}
.xuanzhe:last-child:nth-child(4n + 2) {
	margin-right: calc((100% - 23%) / 3 * 2);
}
.xuanzhe:last-child:nth-child(4n + 3) {
	margin-right: calc((100% - 23%) / 3 * 1);
}
</style>
